package com.xiaoyao.novel.velocity;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.xiaoyao.novel.common.Pagin;
import com.xiaoyao.novel.pojo.Book;
import com.xiaoyao.novel.pojo.Category;
import com.xiaoyao.novel.pojo.Chapter;
import com.xiaoyao.novel.pojo.WebInfo;
import com.xiaoyao.novel.service.BookService;
import com.xiaoyao.novel.service.CategoryService;
import com.xiaoyao.novel.service.ChapterService;
import com.xiaoyao.novel.service.WebInfoService;
import com.xiaoyao.novel.util.FileUtil;
import com.xiaoyao.novel.util.SpendClock;

/**
 * 测试类
 * @author Administrator
 *
 */
public class VelocityMain {
	static Logger logger = Logger.getLogger(VelocityMain.class);
	static VelocityEngine ve = new VelocityEngine();

	public static String webRoot = FileUtil.getWebRoot();
	public static String phoneDir = "m/";
	public static String bookDir = "book/";
	public static String chapterDir = "chapter/";
	public static String templateDir = webRoot;

	static {
		// 初始化
		Properties properties = new Properties();
		// 指定,如"D:/template",但记住只要指定到文件夹就行了
		properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templateDir+phoneDir); // 此处的fileDir可以直接用绝对路径来
		properties.setProperty("input.encoding", "UTF-8");
		properties.setProperty("output.encoding", "UTF-8");
		properties.setProperty("file.resource.loader.cache", "true");
		try {
			ve.init(properties);
		} catch (Exception e) {
			logger.error(e);
		}
	}
	/**
	 * Velocity 静态化页面,
	 * 
	 * @param context
	 *            上下文参数,Map 形式的数据
	 * @param templateFilepath
	 *            模板地址,WebRoot相对 地址
	 * @param outputFilepath
	 *            输出文件地址,绝对地址
	 * @return 静态页面的内容
	 */
	public static String staticPage(VelocityContext context, String templateFilepath, String outputFilepath) {
		String result = "处理错误:请返回";
		try {
			Template template = ve.getTemplate(templateFilepath);
			StringWriter stringWriter = new StringWriter();
			template.merge(context, stringWriter);

			PrintWriter filewriter = new PrintWriter(
					new OutputStreamWriter(new FileOutputStream(outputFilepath), "GBK"), true);
			result = stringWriter.toString();
			filewriter.println(result);
			filewriter.close();
		} catch (Exception e) {
			logger.error(e);
		}
		return result;
	}

	public static void test() {
		// 取得velocity上下文
		VelocityContext context = new VelocityContext();
		// 放入数据
		WebInfo webInfo = new WebInfo();
		context.put("name", "旷逍遥");
		context.put("webInfo", webInfo);
		String templateFilepath = "m/test.vm";
		String outputFilepath = "F:\\a.html";
		String html = staticPage(context, templateFilepath, outputFilepath);
		System.out.println(html);

	}

	public static void staticBookAll() {
		WebInfoService webInfoService = new WebInfoService();
		CategoryService categoryService = new CategoryService();
		BookService bookService = new BookService();
		ChapterService chapterService = new ChapterService();
		int bookId = 355;
		int size = 9;

		WebInfo webInfo = webInfoService.getStaticWebInfo();
		List<Category> categoryList = categoryService.getAll();

		Pagin pagin = new Pagin();
		pagin.setPageSize(size);
		pagin.getSearchParam().put("orderBy", " clickCount desc");
		List<Book> hotList = bookService.search(pagin);

		pagin = new Pagin();
		pagin.setPageSize(size);
		pagin.setStart(0);
		pagin.getSearchParam().put("orderBy", " isRecommend desc, clickCount desc ");
		List<Book> recommendList = bookService.search(pagin);

		Book book = bookService.getById(bookId);

		pagin = new Pagin();
		pagin.setPageSize(10000);
		pagin.getSearchParam().put("orderBy", " cid asc ");
		pagin.getSearchParam().put("bookId", book.getBookId() + "");
		List<Chapter> chapterList = chapterService.search(pagin);
		book.setList(chapterList);

		VelocityContext context = new VelocityContext();
		context.put("webInfo", webInfo);
		context.put("templateDir", templateDir);
		context.put("book", book);
		context.put("hotList", hotList);
		context.put("categoryList", categoryList);
		context.put("recommendList", recommendList);

		String bookTemplateFilepath =  "book.vm";
		String bookOutputFilepath = webRoot + phoneDir + bookDir + bookId + ".html";

		SpendClock.start();
		String html = staticPage(context, bookTemplateFilepath, bookOutputFilepath);
		SpendClock.print();
		System.out.println("输出地址:" + bookOutputFilepath);
		int chapterSize = book.list.size();
		for (int i = 0; i < chapterSize; i++) {
			Chapter chapter = book.list.get(i);
			if (i > 1) { // 有前一张
				chapter.setPrevId(book.list.get(i - 1).getCid());
			}
			if (i < chapterSize - 1) { // 有后一张
				chapter.setNextId(book.list.get(i + 1).getCid()); 
			}

			context.put("chapter", chapter);

			String chapterTemplateFilepath = "chapter.vm";
			String chapterOutputFilepath = webRoot + phoneDir + chapterDir + chapter.getCid() + ".html";

			SpendClock.start();
			html = staticPage(context, chapterTemplateFilepath, chapterOutputFilepath);
			SpendClock.print();
			System.out.println("输出地址:" + chapterOutputFilepath);
		}

	}

	public static void main(String[] args) {
		SpendClock.start();
		staticBookAll();
		// testtt() ;
		SpendClock.print();
	}

	static void testtt() {
		try {
			// 初始化
			Properties properties = new Properties();
			VelocityEngine ve = new VelocityEngine();
			String dir = FileUtil.getWebRoot();
			// 指定,如"D:/template",但记住只要指定到文件夹就行了
			properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, dir); // 此处的fileDir可以直接用绝对路径来
			properties.setProperty("input.encoding", "UTF-8");
			properties.setProperty("output.encoding", "gbk");
			properties.setProperty("file.resource.loader.cache", "true");
			ve.init(properties); // 初始化

			// 取得velocity上下文
			VelocityContext context = new VelocityContext();
			// 放入数据
			WebInfo webInfo = new WebInfo();
			context.put("name", "旷逍遥");
			context.put("webInfo", webInfo);

			Template template = ve.getTemplate("m/test.vm");
			StringWriter writer = new StringWriter();
			template.merge(context, writer);

			PrintWriter filewriter = new PrintWriter(new FileOutputStream("F:\\a.html"), true);
			String result = writer.toString();
			System.out.println(result);
			filewriter.println(result);
			filewriter.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
